package com.ditty.server.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ditty.HttpConfiguration;
import com.ditty.server.IServer;

/**
 * @author dingnate
 */
public final class NettyServer implements IServer {

	private static transient final Logger LOG = LoggerFactory.getLogger(NettyServer.class);

	private Channel ch;

	@Override
	public void start() {
		start("resources", HttpConfiguration.DEFAULT_PORT, "/");
	}

	public static void main(String[] args) throws Exception {
		IServer server = new NettyServer();
		server.start();
	}

	@Override
	public void start(String webDir, final int port, String contextPath) {
		// 准备配置
		HttpConfiguration.me().setContextPath(contextPath).setWebDir(webDir).config();
		// 启动服务器
		NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
		NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);
		try {
			ServerBootstrap boot = new ServerBootstrap();
			options(boot).group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new ServerInitializer());
			ch = boot.bind(port).sync().channel();
			LOG.error("启动NettyServer成功，绑定端口:{}", port);
			ch.closeFuture().sync();
		} catch (InterruptedException e) {
			LOG.error("启动NettyServer错误", e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	private ServerBootstrap options(ServerBootstrap boot) {
		if (HttpConfiguration.me().getSoBacklog() > 0) {
			boot.option(ChannelOption.SO_BACKLOG, HttpConfiguration.me().getSoBacklog());
		}
		return boot;
	}

	@Override
	public void stop() {
	}
}
